package com.cdtu.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;

import com.cdtu.dto.R;
import com.cdtu.entity.Message;
import com.cdtu.service.MessageService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.stream.Collectors;


/**
 * @author : Sakura
 * @Date : 2023/5/6 16:59
 * @Description : TODO 消息的处理接口类
 */
@RestController
@CrossOrigin
@RequestMapping("api/message")
public class MessageController {
    @Autowired
    private MessageService messageService;

    @PutMapping("/status/{mid}")
    public R changeStatus(@PathVariable("mid") long mid) {
        Message message = messageService.getById(mid);
        message.setStatus(1);
        boolean update = messageService.updateById(message);
        return R.success(update);
    }
    @GetMapping("/total")
    public R changeStatus() {
        List<Message> list = messageService.list();
        long count = list.stream().filter(message -> message.getStatus() == 0).count();
        return R.success(count);
    }

    @GetMapping("/list/{pageNow}/{pageSize}")
    public R list(@PathVariable("pageNow") Integer pageNow,
                  @PathVariable("pageSize") Integer pageSize){
        Page<Message> page = messageService.page(new Page<>(pageNow, pageSize));
        List<Message> collect = page.getRecords().stream().sorted(((m1, m2) -> {
            return -Long.compare(m1.getTime().getTime(), m2.getTime().getTime());
        })).collect(Collectors.toList());
        page.setRecords(collect);
        return R.success(page);
    }

    @DeleteMapping("/delete/{mid}")
    public R delete(@PathVariable Long mid) {
        boolean remove = messageService.removeById(mid);
        if (!remove) {
            return R.error("删除失败");
        }
        return R.success("删除成功");
    }
}
